//
//  NetworkRequest.m
//  CoachsBook
//
//  Created by huiyong li on 2022/9/2.
//

#import "NetworkRequest.h"

@implementation NetworkRequest

#pragma mark - 单例类初始化
+(instancetype) shareCommonRequest {
    static NetworkRequest *instance = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
        instance.afManager = [AFHTTPSessionManager manager];
        
        /**设置超时时间*/
        instance.afManager.requestSerializer.timeoutInterval = 20;
        /**设置相应的缓存策略*/
        instance.afManager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
        /**分别设置请求以及相应的序列化器*/
        instance.afManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        instance.afManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        /**复杂的参数类型 需要使用json传值-设置请求内容的类型*/
        [instance.afManager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        /**设置接受的类型*/
        instance.afManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/javascript",@"text/plain",@"application/text",nil];
        //无条件的信任服务器上的证书
        AFSecurityPolicy *securityPolicy =  [AFSecurityPolicy defaultPolicy];
        // 客户端是否信任非法证书
        securityPolicy.allowInvalidCertificates = YES;
        // 是否在证书域字段中验证域名
        securityPolicy.validatesDomainName = NO;
        instance.afManager.securityPolicy = securityPolicy;
        
    });
    return instance;
}


- (void)startWithPath:(NSString *)path params:(NSDictionary *)dict requestType:(RequestType)requestType sucess:(SuccessBlock)completionBlock FailureBlock:(FailureBlock)failureBlock failBlock:(FailBlock)failBlock{
 
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSMutableDictionary *initDic = [dict mutableCopy];
    
    if (initDic == nil) {
        initDic = [NSMutableDictionary dictionary];
    }
    
    initDic[@"appid"] = AppID;
    initDic[@"device"] = [NSString getDeviceIDFV];//是根据设备uuid去判断是否开通了会员，或者如果登录了手机号也可以其他设备。不然就当前手机可以使用
    NSLog(@"===美妙的uuid： %@",[NSString getDeviceIDFV]);
    
    
    if ([[CBUserConfig shareInstance]getUser_id] && ![[[CBUserConfig shareInstance]getUser_id] isEqual:[NSNull null]]) {
        initDic[@"user_id"] = [NSString stringWithFormat:@"%@",[[CBUserConfig shareInstance]getUser_id]];
    }else{
        initDic[@"user_id"] = @"";
    }
    if ([[CBUserConfig shareInstance]getUkey] && ![[[CBUserConfig shareInstance]getUkey] isEqual:[NSNull null]]) {
        initDic[@"user_key"] = [NSString stringWithFormat:@"%@",[[CBUserConfig shareInstance]getUkey]];
    }else{
        initDic[@"user_key"] = @"";
    }
    NSString *sign = [NSString formInputSign:initDic];
    initDic[@"sign"] = sign;
    

    NSLog(@"请求参数==%@",initDic);
    if (requestType == GETType) {
        [manager GET:path parameters:initDic headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (completionBlock) {
                completionBlock(responseObject);
            }
                    
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failureBlock) {
              failureBlock(error);
          }
        }];
    }else if (requestType == POSTType) {
        [manager POST:path parameters:initDic headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (completionBlock) {
                completionBlock(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failureBlock) {
             failureBlock(error);
         }
        }];
    }
}


#pragma mark -网络请求
/// @param params  请求参数
/// @param path 请求地址
/// @param requestType 请求类型
/// @param successBlock  成功返回
/// @param failBlock 失败返回
/// @param failure 失败返回
- (void)requestWithParams:(NSDictionary *)params Path:(NSString *)path requestType:(RequestType)requestType success:(SuccessBlock)successBlock fail:(FailBlock)failBlock failure:(void(^)(NSError *error))failure
{
    NSString *requestpath = [NSString stringWithFormat:@"%@%@", baseUrl, path];
    
    [NetworkRequest.shareCommonRequest startWithPath:requestpath params:params requestType:GETType sucess:^(id  _Nonnull result) {
        [self checkResult:result ok:^(id result) {
            
            NSLog(@"\nAllUrl=%@ \n请求参数=%@ \n返回结果=%@",requestpath,params,result);
            if (successBlock) {
                successBlock(result);
            }
             } fail:^(NSInteger code, NSString * msg) {
                 if (failBlock) {
                     failBlock(code,msg);
             }
         }];
        
      } FailureBlock:^(NSError * _Nonnull error) {
          if (failure) {
            failure(error);
          }
      } failBlock:^(NSInteger code, NSString * _Nonnull msg) {
          if (failBlock) {
              failBlock(code,msg);
          }
      }];
}


-(void)checkResult:(NSDictionary *)result ok:(void (^)(id _Nonnull))ok fail:(void (^)(NSInteger, NSString * _Nonnull))fail{
    
    NSInteger code = [[result objectForKey:@"code"]intValue];
    if (code==200) {
        ok(result);
    }
    else
    {
        NSInteger code = [[result objectForKey:@"code"]intValue];
        NSString *message = [result objectForKey:@"msg"];
        fail(code, message);
    }
}


@end
